package com.qf.smartplatform.event.listener;

import com.qf.smartplatform.event.LoginFailEvent;
import com.qf.smartplatform.event.LoginSuccessEvent;
import com.qf.smartplatform.pojo.BaseUser;
import com.qf.smartplatform.pojo.SysLogininfor;
import com.qf.smartplatform.pojo.SysUserOnline;
import com.qf.smartplatform.service.LoginService;
import com.qf.smartplatform.service.OnlineUserService;
import com.qf.smartplatform.service.UserService;
import com.qf.smartplatform.utils.RequestUtil;
import com.qf.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.task.TaskExecutor;
import org.springframework.security.access.event.AuthorizationFailureEvent;
import org.springframework.security.authentication.event.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class LoginEventListener {
    private LoginService loginService;
    @Autowired
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }
    private OnlineUserService onlineUserService;
    @Autowired
    public void setOnlineUserService(OnlineUserService onlineUserService) {
        this.onlineUserService = onlineUserService;
    }
    private TaskExecutor taskExecutor;
    @Autowired
    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }
    private UserService userService;
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

//    @Async//异步执行
    @EventListener
    public void onEvent(AuthenticationSuccessEvent event) throws InterruptedException {
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaa");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteHost();
        BaseUser baseUser = (BaseUser) event.getAuthentication().getPrincipal();

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //开启异步
        CompletableFuture.runAsync(()->{
            userService.updateLoginData(baseUser.getuId(),ip);
        },taskExecutor);
        String id = request.getSession().getId();
        Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
        String os = osAndBrowserInfo.get("os");
        String browser = osAndBrowserInfo.get("browser");
        String locationByIp = RequestUtil.getLocationByIp(ip);
        CompletableFuture.runAsync(()->{
            SysUserOnline sysUserOnline = new SysUserOnline();
            sysUserOnline.setSessionId(id);
            sysUserOnline.setLoginName(baseUser.getUsername());
            sysUserOnline.setOs(os);
            sysUserOnline.setBrowser(browser);
            sysUserOnline.setIpaddr(ip);
            sysUserOnline.setLoginLocation(locationByIp);
            sysUserOnline.setStatus("1");
            sysUserOnline.setExpireTime(30L);
            sysUserOnline.setStartTimestamp(new Date());
            sysUserOnline.setLastAccessTime(new Date());
            onlineUserService.addOnlineData(sysUserOnline);
        },taskExecutor);

        CompletableFuture.runAsync(()->{

            SysLogininfor sysLogininfor = addLog(osAndBrowserInfo, ip, baseUser.getUsername());
            sysLogininfor.setStatus("1");
            sysLogininfor.setMsg("登陆成功");
            loginService.addLog(sysLogininfor);

        },taskExecutor);
    }
    @EventListener
private void onLoginFail(AbstractAuthenticationFailureEvent event){
        System.out.println("登录失败执行了++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        System.out.println(event.getAuthentication().getPrincipal());
        String userName = (String) event.getAuthentication().getPrincipal();
        if (userName == null) {
                return;
            }

        System.out.println(userName );
        //获取到request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();


        //根据请求头user-agent获取用户得浏览器，操作系统
        Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
        String ip = request.getRemoteHost();
        //在异步中添加数据
        CompletableFuture.runAsync(()->{
            SysLogininfor sysLogininfor = addLog(osAndBrowserInfo, ip,userName);
            sysLogininfor.setStatus("0");
            sysLogininfor.setMsg("登陆失败");
            //同时插入到登录日志中
            loginService.addLog(sysLogininfor);
        },taskExecutor);

    }

    public SysLogininfor addLog(Map<String, String> osAndBrowserInfo,String ip ,String username ){
        String os = osAndBrowserInfo.get("os");
        String browser = osAndBrowserInfo.get("browser");

        System.out.println("+++++++++++++++++"+os);
        System.out.println("+++++++++++++++++"+browser);

        String locationByIp = RequestUtil.getLocationByIp(ip);
        SysLogininfor sysLogininfor = new SysLogininfor();
            sysLogininfor.setLoginName(username);
            sysLogininfor.setIpaddr(ip);
            sysLogininfor.setLoginLocation(locationByIp);
            sysLogininfor.setBrowser(browser);
            sysLogininfor.setOs(os);

            sysLogininfor.setLoginTime(new Date());


        return sysLogininfor;
    }
}
